package com.blogs.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import android.util.Log;

import com.blogs.entity.AppConfig;
import com.blogs.entity.AppEnums.EnumContentType;
import com.blogs.entity.CommentFeed;
import com.blogs.entity.MsgEntity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GetCommentLine {
	public interface IMsgCallBack {
		public void onSuccess(ArrayList<CommentFeed> feedList);
		public void onFailed();
	}
	private String url="";
	private GetMsgTask timeLine;
    private IMsgCallBack callback;
	public GetCommentLine(int type,String comment_id,int page,IMsgCallBack callback)
	{
		this.callback=callback;
		timeLine=new GetMsgTask(taskCallBack);
		if(type==EnumContentType.blog||type==EnumContentType.search_blog_detail)
		{
			url=AppConfig.GET_BLOG_COMMENT_LINE_URL;
		}
		else
		{
			url=AppConfig.GET_NEW_COMMENT_LINE_URL;
		}
		url=url.replace("{0}", comment_id).replace("{1}", page+"");
	}
	public void loadData()
	{
		timeLine.execute(url);
	}
	private GetMsgTask.onTaskCallBack taskCallBack=new GetMsgTask.onTaskCallBack() {
		
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			
			
			GsonBuilder builder = new GsonBuilder();
			Gson gson = builder.create();
			MsgEntity<ArrayList<Object>> msg=null;
			try
			{
				msg=gson.fromJson(result,MsgEntity.class);
			}
			catch(Exception e)
			{
				callback.onFailed();
				return;
			}
			if(msg.op.equals(""))
			{
				callback.onFailed();
				return;
			}
			ArrayList<CommentFeed> feeds=new ArrayList<CommentFeed>();
			Iterator<Object> iterator = msg.data.iterator();
			int i=0;
			while (iterator.hasNext()) 
			{
				i++;
				Map<String, Object> objs = (Map<String, Object>) iterator.next();
				CommentFeed feed = new CommentFeed(objs);
				feeds.add(feed);
			}
			Log.i("feeds", feeds.size()+","+i);
			callback.onSuccess(feeds);
			Log.i("GetMsgTask", "Success");
		}
		
		public void onFailed() {
			// TODO Auto-generated method stub
			callback.onFailed();
			Log.i("GetMsgTask", "Failed");
		}
	};
}
